<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BScreenAddApp
 *
 * @author jianfeng
 */
class BScreenAddApp extends BUIScreen {

    //put your code here

    public function onRender($data = null) {
        if (!is_array($data)) {
            $data = array();
        }

        $isRenderInitialView = true;

        $model = new CreateSpaceFormModel();

        if ($this->isLinkClicked('addSpaceBtn')) {

            if (isset($_POST['CreateSpaceFormModel'])) {
                $model->attributes = $_POST['CreateSpaceFormModel'];
            }

            $result = $this->addApps($model->Apps);
            $this->gotoUINode(Blyn::app()->getActiveSpace()->getId());
            yii::app()->end();
        }

        if ($isRenderInitialView) {
            $this->addRenderView('addAppView', 'addApp', array('model' => $model, 'screen' => $this));
            //$this->startRender();
        }
    }

    public function getAppsData() {

        //$space = $this->getUINode()->getContextVariable(BScreenCreateSpaceMeta::Context_VARIABLE_NEWSpace);
        //$db = $space->getSpaceEngine()->getDbAdapter();
        //$apps = $db->getApps($space->getId());



        $space = Blyn::app()->getActiveSpace();

        $db = Blyn::app()->getAppDb();

        $apps = $db->getVisibleApps($space);

        $myApps = Blyn::app()->getActiveSpace()->getApps();

        $ids = array();

        foreach ($apps as $app) {
            array_push($ids, $app->getId());
        }

        foreach ($myApps as $app) {
            $appId = $app->getId();
            if (in_array($appId, $ids)) {
                unset($apps[$appId]);
            }
        }

        $data = array();

        foreach ($apps as $app) {
            if ($app->isVisible($space)) {
                $data[$app->getId()] = $app->getName();
            }
        }
        return $data;
    }

    public function addApps($sApps) {
        $spaceId = Blyn::app()->getActiveSpace()->getId();

        foreach ($sApps as $appId) {
            $result = Blyn::app()->getActiveApp()->doOperation(BSpaceEngine::ADDAppOPERATION, array('Space' => $spaceId, 'App' => $appId));
        }
    }

}

?>
